import React, { Component, Fragment } from 'react';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import moment from 'moment';
import { Map, Polyline, Markers, Marker } from 'react-amap';
import { connect } from 'dva';
import fetch from 'dva/fetch';
import {
  Button,
  Row,
  Col,
  Card,
  Modal,
  Icon,
  List,
  Pagination,
  Tooltip,
  message,
} from 'antd';
import DescriptionList from '@/components/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import styles from './AdvancedProfile.less';
import router from 'umi/router';
import blueMarker from '@/assets/location_blue.png';
import yellowMarker from '@/assets/location_yellow.png';
import userMarker from '@/assets/location_current.png';

const { Description } = DescriptionList;

const getWindowWidth = () => window.innerWidth || document.documentElement.clientWidth;
const getWindowHeight = () => window.innerHeight || document.documentElement.clientHeight;

function renderMarker(extData) {
  // const src = extData.last ? blueMarker : yellowMarker;
  const img = <img src={yellowMarker} alt="marker" style={{width: 27, height: 53, position: 'relative', top: -10, left: -4}} />;
  const locateTime = moment.unix(extData.created).format('YYYY-MM-DD HH:mm');
  return extData.last ? <Tooltip title={extData.location} trigger="click">{img}</Tooltip> : img;
}

export default
@connect(({ post, loading }) => ({
  detail: post.detail,
  trackList: post.trackList,
  loading: loading.effects['post/fetchPost'],
}))
class AdvancedProfile extends Component {
  state = {
    modalWidth: 520,
    modalHeight: 400,
    modalVisible: false,
    isWide: true,
    currentPosition: null,
    zoom: 13,
  };

  columns = [
    {
      title: '用户昵称',
      dataIndex: 'log_username',
    },
    {
      title: '最近关怀地址',
      dataIndex: 'log_location',
    },
    {
      title: '最近关怀时间',
      dataIndex: 'log_created',
      render: val => <span>{moment.unix(val).format('YYYY-MM-DD HH:mm')}</span>,
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, record)}>关怀信息</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.handleRefresh();

    this.setModalSize();
    window.addEventListener('resize', this.setModalSize, { passive: true });
    this.getLocation();

    this.mapEvents = {
      created: (ins) => {
        this.mapInstance = ins;
        setTimeout(() => {
          this.mapInstance.setFitView();
        }, 500);
      },
    };
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.setModalSize);
    this.setModalSize.cancel();
  }

  getLocation = () => {
    const geoOptions = {
      enableHighAccuracy: true,
      timeout: 10000
    };
    navigator.geolocation.getCurrentPosition((position) => {
      this.setCurrentLocation(position.coords);
    }, (error) => {
      message.error(`获取位置失败：${error.message}`);
    }, geoOptions);
    navigator.geolocation.watchPosition((position) => {
      this.setCurrentLocation(position.coords);
    }, (error) => {
      message.error(`获取位置变化失败：${error.message}`);
    }, geoOptions);
  }

  setCurrentLocation(coords) {
    const url = `https://restapi.amap.com/v3/assistant/coordinate/convert?locations=${coords.longitude},${coords.latitude}&coordsys=gps&key=bfddc271046914416457f3e8286aa5d2`;
    fetch(url, {mode: 'cors'}).then((ret)=> {
      ret.json().then((data)=> {
        const newCoords = data.locations.split(',');
        this.setState({currentPosition: newCoords});
      })
    });
  }

  @Bind()
  @Debounce(200)
  setModalSize() {
    const w = getWindowWidth();
    const h = getWindowHeight();
    this.setState({
      modalWidth: w - 40,
      modalHeight: h - 55 - 80,
      isWide: w > 600,
    });
  }

  handleCancel = () => {
    this.setState({modalVisible: false});
  }

  handleChangeMobilePage = (current) => {
    const { dispatch, match } = this.props;
    const { params } = match;
    dispatch({
      type: 'post/fetch',
      payload: {
        id: params.id,
        p: current,
      },
    });
  }

  handleRefresh = () => {
    const { dispatch, match } = this.props;
    const { params } = match;
    dispatch({
      type: 'post/fetchPost',
      payload: {
        id: params.id,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch, match } = this.props;
    const { params } = match;

    dispatch({
      type: 'post/fetchPost',
      payload: {
        id: params.id,
        p: pagination.current,
        pageSize: pagination.pageSize,
      },
    });
  };

  showPreview = () => {
    const {protocol, hostname} = window.location;
    const {detail} = this.props;
    const previewUrl = `${protocol}//${hostname}/track/index.php/Post/${detail.post_id}?preview=1`;
    window.open(previewUrl, '_blank');
  }

  handleModalVisible(visible, record) {
    this.props.dispatch({type: 'post/fetchTrackList', payload: {
      log_post_id: record.log_post_id,
      log_user_openid: record.log_user_openid,
    }});
    this.setState({modalVisible: visible});
    setTimeout(() => {
      if(this.mapInstance) this.mapInstance.setFitView();
    }, 500);
  }

  render() {
    const { modalVisible, modalWidth, modalHeight, isWide, currentPosition, zoom } = this.state;
    const { detail, loading, trackList } = this.props;

    const path = [];
    trackList.forEach(item=> {
      if(item.log_position) {
        const lnglat = JSON.parse(item.log_position);
        path.push({
          ...item,
          longitude: lnglat[0],
          latitude: lnglat[1],
        });
      }
    });

    const markers = path.map((item, index) => {
      return {
        position: item,
        last: index === path.length - 1,
        location: item.log_location,
        created: item.log_created,
      }
    });

    const trackData = detail.track || {};

    const {protocol, hostname} = window.location;
    const thumbUrl = `${protocol}//${hostname}/track/Uploads/thumb/${detail.post_thumb_url}`;
    const extra = [
      <Button key="back" size="large" className={styles.detailButton} onClick={()=>{router.push('/list');}} style={{marginRight: 8}}>返回</Button>,
      <Button key="reload" size="large" className={styles.detailButton} onClick={this.handleRefresh}><Icon type="reload" /> 刷新</Button>
    ];

    let currentMarker = null;
    if(currentPosition){
      currentMarker = (
        <Marker position={{longitude: currentPosition[0], latitude: currentPosition[1] }}>
          <img src={userMarker} alt="user-marker" style={{width: 36, height: 36, position: 'relative', top: 0, left: 0}} />
        </Marker>
      );
    }

    return (
      <PageHeaderWrapper>
        <Card title="关怀信息" extra={extra} style={{ marginBottom: 24 }} bordered={false}>
          {isWide ? <StandardTable
            rowKey="log_id"
            selectedRows={[]}
            loading={loading}
            data={trackData}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          /> : 
          <div>
            <List
              itemLayout="vertical"
              pagination={false}
              dataSource={trackData.list || []}
              renderItem={item=> (
                <List.Item
                  key={item.log_id}
                  actions={[]}
                  extra={<a onClick={() => this.handleModalVisible(true, item)}><Icon type="environment" /> 关怀信息</a>}
                  style={{marginBottom: 0}}
                >
                  <List.Item.Meta
                    title={`用户：${item.log_username}`}
                    description={<div><div>最近位置：{item.log_location}</div><div>关怀时间：{moment.unix(item.log_created).format('YYYY-MM-DD HH:mm')}</div></div>}
                    style={{marginBottom: 0}}
                  />
                </List.Item>
              )}
            />
            <div style={{textAlign: 'right'}}>
              <Pagination current={(trackData.pagination || {}).current} total={(trackData.pagination || {}).total} onChange={this.handleChangeMobilePage} />
            </div>
          </div>}
        </Card>
        <Modal
          title="关怀信息"
          visible={modalVisible}
          onCancel={this.handleCancel}
          footer={null}
          width={modalWidth}
          bodyStyle={{height: modalHeight, padding: 0}}
          centered
        >
          <div style={{width: modalWidth, height: modalHeight}}>
            <Map 
              amapkey='b3d7e7bb583bf65f14ef2de8a2e4b91b'
              plugins={['Scale', 'OverView', 'ToolBar']}
              events={this.mapEvents}
            >
              <Polyline path={path} visible style={{strokeStyle: 'dashed'}} />
              <Markers markers={markers} render={renderMarker} />
              {currentMarker}
            </Map>
          </div>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
